import zipfile
import os
import xml.etree.ElementTree as ET


def unzip_document(file_path, output_dir):
    """
    解压文件，ofd,docx
    :param file_path: 文档的路径
    :param output_dir: 解压内容的输出目录
    """
    with zipfile.ZipFile(file_path, 'r') as zip_ref:
        zip_ref.extractall(output_dir)
def parse_document_xml(output_dir):
    # 查找并解析 document.xml 文件
    for root, dirs, files in os.walk(output_dir):
        for file in files:
            if file.startswith('document') and file.endswith('.xml'):
                xml_path = os.path.join(root, file)
                return parse_xml(xml_path)
                #return parse_xml_with_attributes(xml_path)
    return ""

def parse_xml(xml_path):
    # 解析 XML 文件并提取文本内容
    tree = ET.parse(xml_path)
    root = tree.getroot()

    # 遍历 XML 树并提取文本内容
    def extract_text(element):
        text = []
        for child in element:
            if child.text is not None:
                text.append(child.text.strip())
            text.extend(extract_text(child))
        return ' '.join(text)

    return extract_text(root)




def parse_xml_with_attributes(xml_file_path):
    # 解析XML文件
    tree = ET.parse(xml_file_path)
    root = tree.getroot()
 
    # 遍历XML树并打印元素及其属性
    def print_element_with_attributes(element, indent=0):
        # 打印元素标签和属性
        print(' ' * indent + f'<{element.tag}')
        for key, value in element.attrib.items():
            print(' ' * (indent + 2) + f'{key}="{value}"')
        
        # 递归打印子元素
        for child in element:
            print_element_with_attributes(child, indent + 4)
        
        # 打印元素结束标签（可选）
        print(' ' * indent + f'/>' if child is None else ' ' * indent + f'</{element.tag}>')
 
    # 开始打印从根元素开始
    print_element_with_attributes(root)

if __name__ == "__main__":

    # 使用示例
    file_path = '1.ofd'  # Word文档的路径
    output_directory = 'extracted'  # 输出目录
    
    # 确保输出目录存在
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)
    unzip_document(file_path, output_directory)
    document_content = parse_document_xml(output_directory)


    # https://github.com/Gaoyongxian666/OpenSearcher
    #https://2git.xyz/wukonggo/awesome-ofd
    #https://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=3AF6682D939116B6F5EED53D01A9DB5D
    #https://github.com/ofdrw/ofdrw
    #https://gitee.com/ofdrw/ofdrw